<?php

namespace Beerus\Modules\Designer\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Doraemon\model\Designer\DesignerEquity;
use Doraemon\model\Designer\DesignerEquityLog;
use Doraemon\model\Member;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;
use Doraemon\service\User;
use Doraemon\tools\Log;

/**
 * 设计师权益
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */

class DesignerEquityController extends Controller
{
    const PAGE_SIZE = 20;

    const EQUITY_TYPE = [
        1 => '机构子账号绑定',
	    2 => '长视频'
    ];

    const SUB_ACCOUNT_NUMBER = 1;  //机构子账号绑定
    const LONG_VIDEO = 2; //长视频

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $request_data = $request->all();

        $page_size = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);

        $condition = [];
        if (!empty($request_data['uid'])) {
            $condition['uid'] = $request_data['uid'];
        }

        if (!empty($request_data['nick'])) {
            $uid = User::getUidByNick($request_data['nick']);
            $condition['uid'] = $uid;
        }
        if (!empty($request_data['equity_type'])) {
            $condition['equity_type'] = $request_data['equity_type'];
        }

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = DesignerEquity::select('*', $condition);

        $total = 0;
        if (!empty($lists)) {
            unset($condition['ORDER']);
            unset($condition['LIMIT']);
            $total = DesignerEquity::count($condition);
            $user_ids = array_column($lists, 'uid');
            $member_info = Member::getUsers($user_ids);

            foreach ($lists as &$item) {
                $item['nick'] = empty($member_info[$item['uid']]['nick']) ? '' : $member_info[$item['uid']]['nick'];
            }
            unset($item);
        }

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('uid', '用户UID')->placeholder('请输入uid');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('nick', '用户昵称')->placeholder('请输入昵称');
                    });
                    $filter->column(1 / 3, function ($filter) {
                        $filter->equal('equity_type', '权益类别')->select(self::EQUITY_TYPE);
                    });
                    $filter->expand();
                });

                $grid->column("uid", '用户UID');
                $grid->column('nick', '用户昵称');

                $grid->column("type", '权益类别')->display(function () {
                    return self::EQUITY_TYPE[$this->equity_type];
                });
                //如果是长视频权益数和adm权益数显示"-"
                $grid->column("num", '权益数')->display(function () {
                    if ($this->equity_type == self::LONG_VIDEO) {
                        return '-';
                    }
                    return "<a href='/admin/Designer/team/?org_uid={$this->uid}' target='_blank'>{$this->num}</a>";
                });
                $grid->column("adm_num", 'adm权益数')->display(function () {
                    if ($this->equity_type == self::LONG_VIDEO) {
                        return '-';
                    }
                    return $this->adm_num;
                });
                $grid->column("remark", '备注');

                $grid->column("add_time", '创建时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->add_time);
                });

                $grid->column("edit_time", '修改时间')->display(function () {
                    if (empty($this->edit_time)) {
                        return '-';
                    }
                    return date("Y-m-d H:i:s", $this->edit_time);
                });

                $grid->column("data_status", '数据状态')->display(function () {
                    return DesignerEquity::STATUS[$this->data_status];
                });

                $grid->column("admin_id", '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                });
            }
        );

        $tab = new Tab();
        $tab->add('套餐权益列表', $gridList->render());
        $content->row($tab);
        return $content
            ->header('套餐权益列表')
            ->description(' ')
            ->breadcrumb(['text' => '套餐权益列表']);
    }

    public function edit(Request $request, Content $content, $id = 0)
    {
        $request = $request->all();

        if ($id == 0) {
            $is_create = true;
            $header = '添加权益';
        } else {
            $is_create = false;
            $header = '修改权益';
        }

        $tab = new Tab();
        $tab->add('用户权益信息', self::editAction($request, $id, $is_create));
        return $content->header($header)
            ->breadcrumb([
                'text' => '套餐权益列表',
                'url' => route('equity.list')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($request, $id = 0, $is_create = false)
    {
        if ($is_create) {
            $data = [
                'num' => 0,
                'adm_num' => 0
            ];
            $form = new Form($data);
            $form->text('uid', '用户UID')->setWidth(4, 2)->required('不能为空');
            $form->select('equity_type', '权益类别')->setWidth(4, 2)
                ->options(self::EQUITY_TYPE)->when([self::SUB_ACCOUNT_NUMBER], function ($form) {

                    $form->number('num', '权益数')->setWidth(4, 2)->required('不能为空');
                    $form->number('adm_num', '后台权益数')->setWidth(4, 2)->required('不能为空');

                })->required('不能为空');
        } else {
            $data = DesignerEquity::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
            $form->text('uid', '用户UID')->setWidth(4, 2)->readOnly();
            $form->select('equity_type', '权益类别')->setWidth(4, 2)
                ->options(self::EQUITY_TYPE)->readOnly();
            if ($data['equity_type'] == self::SUB_ACCOUNT_NUMBER) {
                $form->number('num', '权益数')->setWidth(4, 2)->required('不能为空');
                $form->number('adm_num', '后台权益数')->setWidth(4, 2)->required('不能为空');
            }
        }


        $form->textarea('remark', '备注')->setWidth(4, 2);
        $form->select('data_status', '数据状态')->default(DesignerEquity::STATUS_NORMAL)
            ->setWidth(4, 2)->options(DesignerEquity::STATUS);
        $form->action('/admin/Designer/equity_list/save');

        if (!$is_create) {
            $form->textarea('reason', '操作原因')->setWidth(4, 2)->required('不能为空');
        }

        return $form->render();
    }

    public function editSubmit(Request $request)
    {
        $request = $request->all();

        $admin_id = Admin::user()->id;
        $data = [
            'uid' => $request['uid'],
            'equity_type' => $request['equity_type'],
            'num' => isset($request['num']) ? $request['num'] : 0 ,
            'adm_num' => isset($request['adm_num']) ? $request['adm_num'] : 0,
            'remark' => $request['remark'],
            'data_status' => $request['data_status'],
            'admin_id' => $admin_id
        ];

        if (isset($request['id'])) {
            $equity = DesignerEquity::getByCondition([
                'id' => $request['id']
            ]);

            $data['edit_time'] = time();
            $rs = DesignerEquity::updateInfo($request['id'], $data);
        } else {
            $data['add_time'] = time();
            $rs = DesignerEquity::create($data);
        }

        if ($rs) {
            if (isset($request['id'])) {
                $title = '修改成功';
                $log_data = [
                    'uid' => $request['uid'],
                    'equity_id' => $request['id'],
                    'equity_type' => $request['equity_type'],
                    'old' => json_encode([
                        'num' => (int)$equity['num'],
                        'adm_num' => (int)$equity['adm_num'],
                        'data_status' => (int)$equity['data_status']
                    ]),
                    'new' => json_encode([
                        'num' => (int)$request['num'],
                        'adm_num' => (int)$request['adm_num'],
                        'data_status' => (int)$request['data_status']
                    ]),
                    'reason' => $request['reason'],
                    'add_time' => time(),
                    'admin_id' => $admin_id
                ];
                DesignerEquityLog::create($log_data);
            } else {
                $title = '添加成功';
            }

            $success = new MessageBag([
                'title' => $title
            ]);

            return redirect('/admin/Designer/equity_list')->with(compact('success'));
        } else {
            if (isset($request['id'])) {
                $title = '修改失败';
            } else {
                $title = '添加失败';
            }

            $error = new MessageBag([
                'title' => $title
            ]);

            return back()->with(compact('error'));
        }
    }

}